<template>
  <div
    ref="editor"
    contenteditable="true"
    class="editor"
    @paste="handlePaste"
    @input="inputText"
    @blur="inputBlur"
    @focus="inputFocus"
    @click.stop="handleClick"
  />
</template>

<script>
import UploaderUtil from '@/utils/upload/UploaderUtil'
import request from '@/utils/request'
import {UPLOAD_URL} from '@/infra/conf/default'

export default {
  name: 'RichTextEditor',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isBlur: true // 解决赋值时光标自动定位到起始位置
    }
  },
  watch: {
    value(val) {
      if (this.isBlur) {
        this.$refs.editor.innerHTML = val
      }
    }
  },
  mounted() {
    this.$refs.editor.innerHTML = this.value
  },
  methods: {
    inputText() {
      this.$emit('input', this.$refs.editor.innerHTML)
    },
    inputFocus() {
      this.isBlur = false
    },
    inputBlur() {
      this.isBlur = true
    },
    keepLastIndex(obj) {
      if (window.getSelection) { // ie11 10 9 ff safari
        obj.focus() // 解决ff不获取焦点无法定位问题
        const range = window.getSelection() // 创建range
        range.selectAllChildren(obj) // range 选择obj下所有子内容
        range.collapseToEnd() // 光标移至最后
      } else if (document.selection) { // ie10 9 8 7 6 5
        const range = document.selection.createRange() // 创建选择对象
        // var range = document.body.createTextRange();
        range.moveToElementText(obj) // range定位到obj
        range.collapse(false) // 光标移至最后
        range.select()
      }
    },
    handleClick(event) {
      // debugger
      // event.target.closest
    },
    handlePaste(event) {
      const items = event.clipboardData && event.clipboardData.items
      let file = null
      if (items && items.length) {
        // 检索剪切板items
        for (var i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            file = items[i].getAsFile()
          }
        }
      }
      if (!file) {
        return
      }
      event.preventDefault()
      const formData = new FormData()
      formData.append('file', file)
      const loadingImg = new Image()
      loadingImg.src = '/loading.gif'
      loadingImg.style.width = '60px'
      loadingImg.style.height = '60px'
      this.$refs.editor.appendChild(loadingImg)
      this.keepLastIndex(this.$refs.editor)
      UploaderUtil.uploadFile({request, uploadUrl: UPLOAD_URL}, {
        file, success: (data) => {
          loadingImg.parentNode.removeChild(loadingImg)
          const img = new Image()
          img.src = data
          this.$refs.editor.appendChild(img)
          this.keepLastIndex(this.$refs.editor)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.editor {
  border-radius: 4px;
  padding: 10px;
  border: 1px solid #ddd;
  min-height: 65px;
  line-height: 1.4;
  overflow-y: auto;

  ::v-deep img {
    max-width: 100%;
  }
}
</style>
